package com.zf.nio.channel;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;

/**
 * TCP 通道
 * @author Zhou Feng
 */
public class ServerSocketChannelDemo01 {
    public static final String GREETING = "Hello java nio.\r\n";

    public static void main(String[] args) throws IOException, InterruptedException {
        int port = 9999;
        ByteBuffer buffer = ByteBuffer.wrap(GREETING.getBytes());

        // 打开ServerSocketChannel
        ServerSocketChannel ssc = ServerSocketChannel.open();
        // 设置监听的端口
        //ssc.socket().bind(new InetSocketAddress(port));
        ssc.bind(new InetSocketAddress(port));
        // 将 channel 设置该为非阻塞模式
        ssc.configureBlocking(false);
        //while (true) {
            System.out.println("Waiting for connections");
            // 在非阻塞模式下，accept() 方法会立刻返回，如果还没有新进来的连接,返回的将是 null
            SocketChannel sc = ssc.accept();
            if (sc == null) {
                System.out.println("null");
                Thread.sleep(2000);
            } else {
                System.out.println("Incoming connection from: " +
                        sc.socket().getRemoteSocketAddress());
                buffer.rewind();
                sc.write(buffer);
                sc.close();
            }
        //}

    }
}
